package com.example.service.impl;

import com.example.algorithm.SnowflakeIdWorker;
import com.example.config.MyService;
import com.example.entity.Collection;
import com.example.entity.Sentence;
import com.example.entity.Topic;
import com.example.repository.CollectionRepository;
import com.example.repository.SentenceRepository;
import com.example.repository.TopicRepository;
import com.example.service.SentenceService;
import com.example.textToVoice.TextToVoice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

@Service
public class SentenceServiceImpl implements SentenceService {

    @Autowired
    private SentenceRepository sentenceRepository;
    @Autowired
    private TopicRepository topicRepository;
    @Autowired
    private CollectionRepository collectionRepository;
    @Autowired
    private MyService myService;

    @Override
    public List<Sentence> getAllSentences(){
        List<Sentence> sentences = sentenceRepository.findAll();
        perfectSentences(sentences);
        return sentences;
    }

    @Override
    public List<Sentence> getSentenceByTopicIdSortByTime(String userId, String topicId){
        List<Sentence> sentences = sentenceRepository.findByTopicId(topicId);
        perfectSentences(sentences);
        setIsCollection(sentences, userId);
        Collections.sort(sentences, new Comparator<Sentence>() {
            @Override
            public int compare(Sentence o1, Sentence o2) {
                if(o1.getCreateAt().before(o2.getCreateAt())){
                    return 1;
                }else {
                    return -1;
                }
            }
        });
        return sentences;
    }

    @Override
    public List<Sentence> getSentenceByTopicIdSortByAcronym(String userId, String topicId){
        List<Sentence> sentences = sentenceRepository.findByTopicId(topicId);
        perfectSentences(sentences);
        setIsCollection(sentences, userId);
        Collections.sort(sentences, new Comparator<Sentence>() {
            @Override
            public int compare(Sentence o1, Sentence o2) {
                int length = Math.min(o1.getContent().length(), o2.getContent().length());
                Character ch1;
                Character ch2;
                for(int i = 0; i < length; i ++){
                    ch1 = o1.getContent().charAt(i);
                    ch2 = o2.getContent().charAt(i);
                    if(ch1 != ch2){
                        return ch1.compareTo(ch2);
                    }
                }
                return 0;
            }
        });
        return sentences;
    }

    @Override
    public Sentence getSentenceById(String sentenceId) {
        try{
            Sentence sentence = sentenceRepository.findById(sentenceId).get();
            sentence.setTopicName(topicRepository.findById(sentence.getTopicId()).get().getName());
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
            sentence.setCreateAtFormat(simpleDateFormat.format(sentence.getCreateAt()));
            sentence.setUpdateAtFormat(simpleDateFormat.format(sentence.getUpdateAt()));
            return sentence;
        }catch (Exception e){
            return new Sentence();
        }
    }

    @Override
    public void addSentence(String topicName, String content){
        Topic topic = topicRepository.findByName(topicName);
        Sentence sentence = new Sentence();
        sentence.setId(SnowflakeIdWorker.generateId() + "");
        sentence.setTopicId(topic.getId());
        sentence.setTopicName(topicName);
        sentence.setContent(content);
        sentence.setCreateBy("admin");
        sentence.setCreateAt(new Date());
        sentence.setUpdateAt(new Date());
        sentence.setUpdateBy("admin");
        sentence.setDel(false);
        sentenceRepository.save(sentence);
        topic.setCount(topic.getCount()+1);
        topic.setUpdateBy("admin");
        topic.setUpdateAt(new Date());
        topicRepository.save(topic);
        try {
            TextToVoice.textToVoice(sentence.getContent(), sentence.getId(), myService.getStandardAudioPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getStandardAudio(String sentenceId){
        try {
            InetAddress address = InetAddress.getLocalHost();
            return "http://" + address.getHostAddress() + ":" + myService.getLocalPort()
                    + "/sentence/getStandardAudio/" + sentenceId + ".mp3";
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 判断句子是否被用户收藏，把判断结果完善到sentence对象中
     * @param sentences 多个句子
     * @param userId 用户id
     */
    private void setIsCollection(List<Sentence> sentences, String userId){
        for (Sentence s:sentences
        ) {
            Collection collection = new Collection();
            try {
                collection = collectionRepository.findByUserIdAndSentenceId(userId, s.getId());
            }catch (Exception e){
                e.printStackTrace();
            }
            if(collection!=null){
                s.setCollection(true);
            }
        }
    }

    /**
     * 完善句子对象的所有信息（某些信息没有保存再数据库）
     * @param sentences 句子列表
     */
    private void perfectSentences(List<Sentence> sentences){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
        for (Sentence s:sentences
        ) {
            s.setCreateAtFormat(simpleDateFormat.format(s.getCreateAt()));
            s.setUpdateAtFormat(simpleDateFormat.format(s.getUpdateAt()));
            s.setTopicName(topicRepository.findById(s.getTopicId()).get().getName());
        }
    }

}
